package com.zenithsun.common.review.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.CriteriaSpecification;
import org.springframework.stereotype.Repository;

import com.syzg.common.util.SearchMap;
import com.zenithsun.common.dao.NativeSQLDaoHibernate;
import com.zenithsun.common.review.dao.ReviewDAO;
import com.zenithsun.common.review.model.Review;
import com.zenithsun.news.newscolumns.model.NewsColumns;

@Repository("reviewDao")
public class ReviewDAOImpl extends NativeSQLDaoHibernate<Review> implements ReviewDAO {

	@Override
	protected Class<Review> getEntityClass() {
		return Review.class;
	}
	
	/**
	 * 
	 * @param review
	 * @return
	 */
	private String createUpdateSQL(Review review){
		StringBuffer sb=new StringBuffer();
		if(review!=null&&StringUtils.isNotBlank(review.getId())){
			sb=new StringBuffer("UPDATE REVIEW SET");
			sb.append(" ID='").append(review.getId()).append("'");
			if(StringUtils.isNotBlank(review.getComments())){
				sb.append(",comments='").append(review.getComments()).append("'");
			}
			if(review.getState()>-1){
				sb.append(",state=").append(review.getState());
			}
			sb.append(" WHERE ID='").append(review.getId()).append("'");
		}
		if(sb.length()==0){
			return null;
		}
		return sb.toString();
	}
	
	@Override
	public boolean updateNotBlank(Review review) throws Exception {
		String sql=createUpdateSQL(review);
		if(sql==null){
			return false;
		}
		try{
			return executeSql(sql)>0;
		}catch(Exception ex){
			return false;
		}finally{
		}
	}

	@Override
	public Review getReviewByBus(String busId, String busMark) throws Exception {
		SQLQuery query=getSession().createSQLQuery("SELECT R.* FROM REVIEW R WHERE R.BUSID=? AND R.BUS_MARK=?");
		query.addEntity(getEntityClass());
		query.setParameter(0,busId);
		query.setParameter(1,busMark);
		List list=query.list();
		if(list!=null&&list.size()>0){
			return (Review)list.get(0);
		}
		return null;
	}
	
	@Override
	public Integer queryPicReview() throws Exception{
		SQLQuery picQuery=getSession().createSQLQuery("SELECT COUNT(*) totalCount FROM PICSUBJECT P LEFT JOIN (SELECT V.state,V.ID reviewId,V.busId FROM REVIEW V WHERE V.BUS_MARK='Pic') N ON P.ID = N.BUSID WHERE N.STATE='1'");
		Long picCount = Long.parseLong(picQuery.uniqueResult().toString());
		Integer picReviewCounter= picCount.intValue();
		return picReviewCounter;
	}
	
	@Override
	public Integer queryNewsReview() throws Exception{
		SQLQuery newsQuery=getSession().createSQLQuery("SELECT COUNT(*) totalCount FROM NEWSINFO P LEFT JOIN (SELECT V.state,V.ID reviewId,V.busId FROM REVIEW V WHERE V.BUS_MARK='News') N ON P.ID = N.BUSID WHERE N.STATE='1' AND ISDELETE=0");
		Long newsCount = Long.parseLong(newsQuery.uniqueResult().toString());
		Integer newsReviewCounter= newsCount.intValue();
		return newsReviewCounter;
	}
}
